package com.javaee.tallybook.controller;

import com.javaee.tallybook.pojo.User;
import com.javaee.tallybook.service.UserService;
import com.javaee.tallybook.until.JsonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;
import java.util.Map;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 登录
     * @param name
     * @param pwd
     * @return
     */
    @RequestMapping("/login")
    public ModelAndView Login(
            @RequestParam("name") String name,
            @RequestParam("pwd") String pwd,
            HttpSession session
    ) {
        User result = userService.getUserByNameAndPwd(name, pwd);
        if (result != null) {
            session.setAttribute("name", name);
            return new ModelAndView("redirect:/index.html");
        } else {
            return new ModelAndView("redirect:/error.html");
        }
    }

    /**
     * 注册
     * @param name
     * @param pwd
     * @return
     */
    @RequestMapping("/reg")
    public ModelAndView Reg(
            @RequestParam("name") String name,
            @RequestParam("pwd") String pwd
    ) {
        User user=new User();
        user.setU_name(name);
        user.setU_pwd(pwd);
        Boolean exist = userService.isExist(name);
        if (!exist){
            return new ModelAndView("redirect:/error.html");
        }
        Integer result = userService.addUser(user);
        if (result > 0) {
            return new ModelAndView("redirect:/login.html");
        } else {
            return new ModelAndView("redirect:/error.html");
        }
    }

    /**
     * 修改密码
     * @param pwd
     * @param session
     * @return
     */
    @RequestMapping("/change")
    public Map<String,Object> Change(
            @RequestParam("pwd") String pwd,
            HttpSession session
    ){
        String name = (String) session.getAttribute("name");
        JsonResult jsonResult=new JsonResult();
        Integer result = userService.changePwd(pwd, name);
        if(result>0){
            jsonResult.setCode(1);
        }else {
            jsonResult.setCode(0);
        }
        return jsonResult.getValues();
    }
}
